package py.com.fms.fms.session.maintenances;

//External classes imports 
//Java Classes
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.faces.event.ActionEvent;

//Seam Classes
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

//project classes imports

import py.com.fms.fms.bean.UsersBean;
import py.com.fms.fms.bean.PersonBean;

import py.com.fms.fms.persistence.services.UsersServices;
import py.com.fms.fms.persistence.services.PersonServices;

import py.com.fms.exception.CommonException;
import py.com.fms.session.PasswordServices;
import py.com.fms.session.ServiceSqlMap;
import py.com.fms.session.WithinHolder;
import py.com.fms.utilities.*;

@SuppressWarnings("unused")
@Name("editUser")
@Scope(ScopeType.SESSION)
public class EditUser {
	private FacesMessages facesMessages;
	@Logger
	private Log log;
	@In("#{serviceSqlMap}")
	private ServiceSqlMap sqlMap;
	private String initVar;
	private Date today = null;
	
	// Task Attendees Attributes 
	
	@In("#{withinHolder}")
	private WithinHolder aid;
	@In("#{convertAssist}")
	private ConvertAssistant convert;
	@In Credentials credentials;
	@In Identity identity;
	
	private DateAssistant dateAssist;

	// Attribute used for saving and deleting
	private UsersBean user;
	private UsersBean userIns;
	
	// Users
	private UsersServices usSrv;
	private PersonServices prSrv;
	private PasswordServices pwSrv;
	
	// Collection of monedasBean
	private Collection<UsersBean> allUsers;

	// Attribute used for editing or updating
	private UsersBean editUser;
	
//	Necessary Attributes;
	
	

	/**
	 * [[[[[[[[[[[[ Methods ]]]]]]]]]]]] 
	 * [[[[[[[[[[-------------]]]]]]]]]]
	 * @throws CommonException 
	 */

	// Used to initialize information from a variable
	public void initData() throws CommonException {

		System.out.println("Initialization Flag = " + this.getInitVar());

		if ("S".equals(this.getInitVar())) {
			this.initBeans();
			this.initServices();
			this.initAssistants();
			this.initCollections();
			this.loadDataGrid();
			
			if(credentials != null){
				System.out.println("Credenciales Encontradas");
				this.getUserIns().setUserName(credentials.getUsername());
				System.out.println("User Name: " + this.getUserIns().getUserName());
				userIns = usSrv.getUserDataByName(this.getUserIns().getUserName());
				this.setUserIns(userIns);
				System.out.println("User: " + this.getUser());
			}else{	
				System.out.println("Credenciales Nulas");
			}
			
		}
		this.setInitVar(null);
		System.out.println("OUT");
				
	}
	
	public void initBeans(){
		
		if (user == null){
			user = new UsersBean();
			user.setStatus(true);
		}
		
		if (userIns == null){
			userIns = new UsersBean();
		}
		
		if (editUser == null){
			editUser = new UsersBean();
		}
	}
	
	public void initServices() throws CommonException{
		
		if (usSrv == null){
			usSrv = new UsersServices(this.sqlMap.getConfig());
		}
		
		if (prSrv == null){
			prSrv = new PersonServices(this.sqlMap.getConfig());
		}
		
		if (pwSrv == null){
			pwSrv = new PasswordServices();
		}
				
	}
	
	public void initAssistants(){
		
		
		if(aid == null){
			aid = new WithinHolder();
		}
		
		if(convert == null){
			convert = new ConvertAssistant();
		}
		
		if(dateAssist == null){
			dateAssist = new DateAssistant();
		}
		
	}
	
	public void initCollections(){
		if(allUsers == null){
			allUsers = new ArrayList<UsersBean>();
		}
		

	}

	// Used to load a grid using a collection
	private void loadDataGrid() {
		try {
			this.setAllUsers(usSrv.getAllUsers());
			for (UsersBean user : this.getAllUsers()) {
				System.out.println(user.getCod());
			}
		} catch (CommonException e) {
			e.printStackTrace();
		}
	}

	// Used to cancel
	public String cancelData() {
//		this.facesMessages.clear();
		this.setInitVar("S");
		return null;
	}
		

	// Used for data saving process
	public void saveNewData() throws ParseException {
		try {
//			this.facesMessages.clear();
			UsersBean newUser = new UsersBean();
			aid = new WithinHolder();
			this.today = DateAssistant.getHoleDateTime();
			
			if (this.getUser() == null) {
				System.out.println("this.getService() == null");
				throw new CommonException("Users Entity is null");
			}
			System.out.println("BEFORE SETTING VALUES");
			
			String hash = pwSrv.encryptPass(this.getUser().getUserPass());
			System.out.println("hash: " + hash);
			// Setting field values
			newUser.setCod(convert.convertField(this.getUser().getCod()));
			newUser.setIdPerson(this.getUser().getPersonData().getId());
			newUser.setUserName(convert.convertField(this.getUser().getUserName()));
			newUser.setUserPass(hash);
			newUser.setStatus(this.getUser().getStatus());
			newUser.setStartDate(this.today);
			newUser.setLastUpdDate(this.today);
			System.out.println(this.today);
			newUser.setUserIns(this.user.getId());
            newUser.setIdEnt(this.getUser().getEntData().getId());
			usSrv.saveNewUsers(newUser);
			
			// Initializing field values
			newUser = null;
			

		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO INSERTAR. " + e.getMessage());
			log.error(e);
		}finally{
			this.setUser(null);
			// Setting Initialization VAR
			this.setInitVar("S");
		}

	}
	
	// Retrieving data for updating
	public void dataToEdit(Long id) throws CommonException{
		System.out.println("id = " + id.toString());
		for (UsersBean bean : this.getAllUsers()) {
			if(bean.getId().equals(id)){
				this.setEditUser(bean);
				this.getEditUser().setPersonData(prSrv.getPersonData(bean.getIdPerson()));
				return;
			}			
		}	
	}
	
	public void dataToEditUpd() throws ParseException{
		try {
			// SETTING EXTERNAL VALUES
			this.today = DateAssistant.getHoleDateTime();
			
			
			// UPDATING EXTERNAL VALUES
			this.getEditUser().setLastUpdDate(this.today);
			
			// SAVING VALUES
			usSrv.updateUsers(this.getEditUser());
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO ACTUALIZAR EL REG. " + e.getMessage());
			log.error(e);
		}
	}
	
	public void dataToDelete(Long id){
		for (UsersBean bean: this.getAllUsers()){
			if (bean.getId() == id) {
				try {
					usSrv.deleteUsersById(bean.getId());
					
				} catch (Exception e) {
//					this.facesMessages.add(Severity.ERROR, e.getMessage());
					System.out.println("NO SE BORRAR EL REGISTRO. " + e.getMessage());
					log.error(e);
				}
			}
			
		}
		this.setInitVar("S");
	}
	
	public Boolean verifyPassword(){
		System.out.println("Verificando Passwords");
		try {
			if (this.getUser().getUserPass() == null	|| this.getUser().getUserPassRepeat() == null) {
				System.out.println("Existen campos vacios");
			} else {
				if (this.getUser().getUserPass().equals(this.getUser().getUserPassRepeat())) {
					System.out.println("Los Password Coinciden");
					return true;
				} else {
					System.out.println("Los Password no Coinciden");
					FacesMessages.instance().add("Los passwords ingresados no coinciden");
				}
			}

		} catch (Error e) {
			FacesMessages.instance().add("Ha ocurrido un error" + e.getMessage());
			
			
		}
		return false;
		
	}

	// GETTERS AND SETTERS
	public FacesMessages getFacesMessages() {
		return facesMessages;
	}

	public void setFacesMessages(FacesMessages facesMessages) {
		this.facesMessages = facesMessages;
	}

	public Log getLog() {
		return log;
	}

	public void setLog(Log log) {
		this.log = log;
	}

	public ServiceSqlMap getSqlMap() {
		return sqlMap;
	}

	public void setSqlMap(ServiceSqlMap sqlMap) {
		this.sqlMap = sqlMap;
	}

	public String getInitVar() {
		return initVar;
	}

	public void setInitVar(String initVar) {
		this.initVar = initVar;
	}

	public UsersBean getUser() {
		return user;
	}

	public void setUser(UsersBean user) {
		this.user = user;
	}

	public Collection<UsersBean> getAllUsers() {
		return allUsers;
	}

	public void setAllUsers(Collection<UsersBean> allUsers) {
		this.allUsers = allUsers;
	}

	public UsersBean getEditUser() {
		return editUser;
	}

	public void setEditUser(UsersBean editUser) {
		this.editUser = editUser;
	}

	public UsersBean getUserIns() {
		return userIns;
	}

	public void setUserIns(UsersBean userIns) {
		this.userIns = userIns;
	}
	
	
}
